<?php

namespace app\api\controller;

use app\common\controller\Api;
use app\common\library\Ems;
use app\common\library\Sms;
use fast\Http;
use fast\Random;
use think\Config;
use think\Validate;
use think\Db;
use think\Cache;
use addons\epay\library\Service;

/**
 * 会员接口
 */
class User extends Api
{
    protected $noNeedLogin = ['login', 'mobilelogin','user_phone','user_phone_dy','loginInfo', 'register', 'resetpwd', 'changeemail', 'changemobile', 'third'];
    protected $noNeedRight = '*';
    public $AppId = 'wxbae1b3248b60e1d8';
    public $Secret = 'b3df3f25537d5c1cdd9ac67e47b7391c';
    public $DouAppId = 'tte3e2955f7cd2a7d301';
    public $DouSecret = '1a8c380ad5fa5b6e3d0455604c47eecf34ba2038';

    public function _initialize()
    {
        parent::_initialize();

        if (!Config::get('fastadmin.usercenter')) {
            $this->error(__('User center already closed'));
        }
    }

    //        getUrl是在common中封装的，封装样式如下
    public function getUrl($url){
        $ch = curl_init();
        curl_setopt($ch, CURLOPT_URL, $url);
        curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, FALSE);
        curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, FALSE);
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
        $output = curl_exec($ch);
        curl_close($ch);
        $output = json_decode($output,true);
        return $output;
    }
    
    
    //获取小程序二维码的token
    public function get_access_token()
    {
        //先判断缓存里面的access_token过期了没有
        if(Cache::get('access_token')){
            //没过期直接拿出来用
            $a = Cache::get('access_token');
            return $a;
        }else{
            //过期了就重新获取
            $appid = $this->AppId;
            $secret = $this->Secret;
            $url = "https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid=$appid&secret=$secret";
            
            //请求接口，获取accesstoken
            $user_obj = $this->curlHttp($url);
            //然后将accesstoken存入缓存里面，官方过期时间7200秒，缓存里面可以过期的早一点，自己把控
            Cache::set('access_token',$user_obj['access_token'],900);

            return Cache::get('access_token');
        }
    }

    function curl_post_https($url, $data, $header = [])
    {
        $ch = curl_init();
        curl_setopt($ch, CURLOPT_URL, $url);
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
        curl_setopt($ch, CURLOPT_POST, true);
        curl_setopt($ch, CURLOPT_POSTFIELDS, $data);
        curl_setopt($ch, CURLOPT_HEADER, $header);
        curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
        curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, false);
        $output = curl_exec($ch);
        curl_close($ch);

        return $output;
    }
    function curlHttp($url)
    {

        $ch = curl_init();
        curl_setopt($ch, CURLOPT_URL, $url);
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
        curl_setopt($ch, CURLOPT_HEADER, false);
        curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
        curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, false);
        $output = curl_exec($ch);
        //释放curl句柄
        curl_close($ch);
        return json_decode($output, true);
    }

    function httpCurl($url,$data=null)
    {
        //初始化
        $ch = curl_init();

        //设置选项，包括URL
        curl_setopt($ch,CURLOPT_URL,$url);
        curl_setopt($ch,CURLOPT_RETURNTRANSFER,1);
        if(!empty($data)){
            curl_setopt($ch,CURLOPT_POST,1);
            curl_setopt($ch,CURLOPT_POSTFIELDS,$data);
        }
        $output = curl_exec($ch);
        curl_close($ch);

        return json_decode($output,true);
    }   
    
     /**
     * 发送post请求
     */
    function json_post($url, $data = [])
    {
        //$data=http_build_query($data);
        //$data=json_encode($data);
        $curl = curl_init();

        curl_setopt($curl, CURLOPT_URL, $url);
        curl_setopt($curl, CURLOPT_SSL_VERIFYPEER, false);
        curl_setopt($curl, CURLOPT_SSL_VERIFYHOST, false);
        if(!$data){
            return 'data is null';
        }
        if(is_array($data))
        {
            $data = json_encode($data);
        }
        curl_setopt($curl, CURLOPT_POST, 1);
        curl_setopt($curl, CURLOPT_POSTFIELDS, $data);
        curl_setopt($curl, CURLOPT_HEADER, 0);
        curl_setopt($curl, CURLOPT_HTTPHEADER,array(
            'Content-Type: application/json; charset=utf-8',
            'Content-Length:' . strlen($data),
            'Cache-Control: no-cache',
            'Pragma: no-cache'
        ));
        curl_setopt($curl, CURLOPT_RETURNTRANSFER, 1);
        $res = curl_exec($curl);
        $errorno = curl_errno($curl);
        if ($errorno) {
            return $errorno;
        }
        curl_close($curl);
        return $res;

    }

     /**
     * 抖音登录【抖音小程序】
     * @ApiMethod (POST)
     * @param string $code
     *
     */
    public function user_phone_dy(){

        // 定义抖音小程序的 appid 和 secretkey
        $appId = $this->DouAppId; // 替换为自己的 AppID
        $secretKey = $this->DouSecret; // 替换为自己的 Secret Key

        $share_type = input('share_type')?input('share_type'):999;//渠道:1=B站,2=微博,3=快手,4=小红书，5=腾讯广告,6=视频号,7=巨量引擎,999=其他
        $share_code = input('share_code');//分享码
        $trackid = input('trackid');//B站的trackid


        $code = input('code');
		$url='https://developer.toutiao.com/api/apps/v2/jscode2session';
        $data=[
            'appid'=>$appId,
            'secret'=>$secretKey,
            'code'=>$code,
            //'anonymous_code'=>$anonymousCode,
        ];
        //  print_r($code);exit;
        $res=$this->json_post($url,$data);
        $resjson=json_decode($res,true);
        
		if ($resjson['err_no']==0){
		    
	    	$openid = $resjson['data']['openid'];
	    	//解密数据
	   // 	echo $openid;exit;
            $user = DB::name("user")->where("openid",$openid)->find();

            if($user){
                $this->auth->direct($user['id']);
                $userinfo = $this->auth->getUserinfo();
                $return = array(
                    "openid" => $openid,
                    "token" => $userinfo['token']
                );

                //B站那边需要在用户进入小程序，回传这个字段，无论这个用户是新用户还是老用户
                if(isset($user['trackid']) && !empty($user['trackid'])){
                    $trackid = $data['trackid'];
                    $conv_time = $this->getMillisecond();
                    //必须要用真实的trackid给B站回传，否则B站那边会报错
                    $b_url = "https://cm.bilibili.com/conv/api/conversion/ad/cb/v1?conv_type=FORM_SUBMIT&conv_time={$conv_time}&track_id={$trackid}";
                    file_put_contents("log/user_FORM_SUBMIT_B".date('Ymd').".txt",$b_url.PHP_EOL,FILE_APPEND);
                    $bili_res = file_get_contents($b_url);
                    file_put_contents("log/user_FORM_SUBMIT_B".date('Ymd').".txt",$bili_res.PHP_EOL,FILE_APPEND);
                    file_put_contents("log/user_FORM_SUBMIT_B".date('Ymd').".txt",date('Y-m-d H:i:s').",已注册用户".PHP_EOL,FILE_APPEND);

                    /**
                     * 用于记录广告数据回传日志，排查广告平台数据与数据库数据对不上的问题
                     */
                    $log_params = [
                        "share_type" => $share_type,
                        "share_code" => $share_code,
                        "url" => $b_url,
                        "res" => $bili_res,
                        "trackid" => $trackid,
                        "company_entity" => $user['company_entity'],
                        "account" => $user['account'],
                        'user_id' => $user['id'],
                    ];
                    $this->save_touliushou_log($log_params,"【抖音小程序】用户登录行为，给B站回传FORM_SUBMIT");
                }
            }else{
                $random = Random::alnum(6);
                $username = "抖音用户".$random;
                $password = $random;
                $domain = request()->host();
                $nickName = $username;
                $system = DB::name("system_info")->where("type",1)->find();
                $system_avatar_count = DB::name("system_avatar")->count();
                if($system_avatar_count > 0){
                    $system_avatar_select = DB::name("system_avatar")->select();
                    $avatar_rand = rand(0,$system_avatar_count-1);
                    $extend['avatar'] = $system_avatar_select[$avatar_rand]['image'];
                }else{
                    $extend['avatar'] = $system['avatar'];
                }
                
                $extend['episode_script_id'] = $system['episode_script_id'];
                
                $eng_system = DB::name("system_info")->where("type",2)->find();
                $extend['eng_episode_script_id'] = $eng_system['episode_script_id'];
                $ri_system = DB::name("system_info")->where("type",3)->find();
                $extend['ri_episode_script_id'] = $ri_system['episode_script_id'];
                $han_system = DB::name("system_info")->where("type",4)->find();
                $extend['han_episode_script_id'] = $han_system['episode_script_id'];
                $extend['openid'] = $openid;
                $extend['reg_type'] = 2;


                $pid_channel_id = 0;
                $pid = 0;
                if($share_code){
                    $pid_user = DB::name("user")->where("share_code",$share_code)->find();
                    if($pid_user){
                        $pid = $pid_user["id"];

                        $pid_channel = DB::name("user_channel")->where(array("user_id"=>$pid,"type"=>$share_type))->find();
                        if($pid_channel){
                            //渠道:1=B站,3=快手,4=小红书，5=微信朋友圈,6=视频号,7=抖音
                            if($share_type == 1){//B站

                                file_put_contents("log/dy_user_loginInfo_B".date('Ymd').".txt","trackid=".$trackid.PHP_EOL,FILE_APPEND);

                                //B站回传
                                $conv_time = $this->getMillisecond();
                                //必须要用真实的trackid给B站回传，否则B站那边会报错
                                if(!empty($trackid)){
//                                $trackid = "pbaes.pUNy4MJ2Ys480sM0UwZGtgegI02oMB26nQ0C1alN0X9S2qnwL5ZtrgEPnAOg9rUnk1bPKVb3pr98wisDlbkQBjPv-LMSPjMLoafocZrveO7ybde8VIaOQCAp7Ztjzark0Sy17q5UQdPNQJzmoeZTxHINFQ_3Luy2jYF142sFoVodPmeRBtZGMmC1G1WrvR2w";
                                    $b_url = "https://cm.bilibili.com/conv/api/conversion/ad/cb/v1?conv_type=USER_REGISTER&conv_time={$conv_time}&track_id={$trackid}";

                                    file_put_contents("log/dy_user_loginInfo_B".date('Ymd').".txt",$b_url.PHP_EOL,FILE_APPEND);
                                    $bili_res = file_get_contents($b_url);
                                    file_put_contents("log/dy_user_loginInfo_B".date('Ymd').".txt",$bili_res.PHP_EOL,FILE_APPEND);
                                    file_put_contents("log/dy_user_loginInfo_B".date('Ymd').".txt","————————————————————————————————————————————————————————————————————".PHP_EOL,FILE_APPEND);


                                    /**
                                     * 用于记录广告数据回传日志，排查广告平台数据与数据库数据对不上的问题
                                     */
                                    $log_params = [
                                        "share_type" => $share_type,
                                        "share_code" => $share_code,
                                        "url" => $b_url,
                                        "res" => $bili_res,
                                        "trackid" => $trackid,
                                        "company_entity" => input('company_entity'),
                                        "account" => input('account'),
                                    ];
                                    $this->save_touliushou_log($log_params,"【抖音小程序】用户注册行为，给B站回传USER_REGISTER");



                                }

                            }else if($share_type == 5){//微信朋友圈(就是广点通,就是腾讯广告)
                                //必须是还没有注册的用户才能绑定渠道关系
                                $isset_user = DB::name("user")->where('openid','=',$extend['openid'])->find();
                                if(empty($isset_user)){
                                    $cpa_teng_xun = DB::name("cpa_teng_xun")->where('wechat_openid','=',$extend['openid'])->order("id","desc")->find();
                                    if(!empty($cpa_teng_xun)){//监测链接里有这一条openid的话，就对上号了
                                        //要向callback的地址提交一个post请求,先拿到callback地址,然后urldecode一下,最后上报注册信息
                                        $post_url = $cpa_teng_xun['callback'];
                                        $post_url = urldecode($post_url);
                                        $post_data['actions'] = [];
                                        $post_data['actions'][0]['action_type'] = "REGISTER";
                                        $post_data['actions'][0]['action_time'] = time();
                                        $post_data['actions'][0]['user_id']['wechat_app_id'] = $this->AppId;
                                        $post_data['actions'][0]['user_id']['wechat_openid'] = $extend['openid'];

                                        file_put_contents("log/dy_user_loginInfo_gdt".date('Ymd').".txt",$post_url.PHP_EOL,FILE_APPEND);
                                        file_put_contents("log/dy_user_loginInfo_gdt".date('Ymd').".txt",json_encode($post_data,JSON_UNESCAPED_UNICODE).PHP_EOL,FILE_APPEND);
                                        $post_res = $this->json_post($post_url,$post_data);
                                        file_put_contents("log/dy_user_loginInfo_gdt".date('Ymd').".txt",$post_res.PHP_EOL,FILE_APPEND);

                                        /**
                                         * 用于记录广告数据回传日志，排查广告平台数据与数据库数据对不上的问题
                                         */
                                        $log_params = [
                                            "share_type" => $share_type,
                                            "share_code" => $share_code,
                                            "url" => $post_url,
                                            "data" => json_encode($post_data,JSON_UNESCAPED_UNICODE),
                                            "res" => $post_res,
                                            "tencentid" =>$cpa_teng_xun['id'],
                                            "company_entity" => input('company_entity'),
                                            "account" => input('account'),
                                        ];
                                        $this->save_touliushou_log($log_params,"【抖音小程序】用户注册行为，给广点通回传REGISTER");




                                        $post_data['actions'][0]['action_type'] = "ACTIVATE_APP";
                                        file_put_contents("log/dy_user_loginInfo_gdt".date('Ymd').".txt",json_encode($post_data,JSON_UNESCAPED_UNICODE).PHP_EOL,FILE_APPEND);
                                        $post_res = $this->json_post($post_url,$post_data);
                                        file_put_contents("log/dy_user_loginInfo_gdt".date('Ymd').".txt",$post_res.PHP_EOL,FILE_APPEND);
                                        file_put_contents("log/dy_user_loginInfo_gdt".date('Ymd').".txt","————————————————————————————————————————————————————————————————————".PHP_EOL,FILE_APPEND);

                                        /**
                                         * 用于记录广告数据回传日志，排查广告平台数据与数据库数据对不上的问题
                                         */
                                        $log_params = [
                                            "share_type" => $share_type,
                                            "share_code" => $share_code,
                                            "url" => $post_url,
                                            "data" => json_encode($post_data,JSON_UNESCAPED_UNICODE),
                                            "res" => $post_res,
                                            "tencentid" =>$cpa_teng_xun['id'],
                                            "company_entity" => input('company_entity'),
                                            "account" => input('account'),
                                        ];
                                        $this->save_touliushou_log($log_params,"【抖音小程序】用户注册行为，给广点通回传ACTIVATE_APP");


                                        $extend['tencentid'] = $cpa_teng_xun['id'];
                                    }
                                }
                            }else if($share_type == 7){//抖音
                                //必须是还没有注册的用户才能绑定渠道关系
                                $isset_user = DB::name("user")->where('openid','=',$extend['openid'])->find();
                                if(empty($isset_user)){
                                    //拿到小程序落地页获得的参数，与监测记录比对
                                    $clickid = input('clickid');
                                    file_put_contents("log/dy_user_loginInfo_dy".date('Ymd').".txt","clickid={$clickid}".PHP_EOL,FILE_APPEND);

                                    if(!empty($clickid)){
                                        $d_url = "https://ad.oceanengine.com/track/activate/?callback={$clickid}&event_type=1";//event_type=1表示注册
                                        file_put_contents("log/dy_user_loginInfo_dy".date('Ymd').".txt",$d_url.PHP_EOL,FILE_APPEND);
                                        $d_res = file_get_contents($d_url);
                                        file_put_contents("log/dy_user_loginInfo_dy".date('Ymd').".txt",$d_res.PHP_EOL,FILE_APPEND);

                                        /**
                                         * 用于记录广告数据回传日志，排查广告平台数据与数据库数据对不上的问题
                                         */
                                        $log_params = [
                                            "share_type" => $share_type,
                                            "share_code" => $share_code,
                                            "url" => $d_url,
                                            "res" => $d_res,
                                            "clickid" => $clickid,
                                            "clue_token" => input('clue_token'),
                                            "company_entity" => input('company_entity'),
                                            "account" => input('account'),
                                        ];
                                        $this->save_touliushou_log($log_params,"【抖音小程序】用户注册行为，给巨量引擎回传event_type=1表示注册");



                                        $d_url = "https://ad.oceanengine.com/track/activate/?callback={$clickid}&event_type=0";//event_type=0表示激活
                                        file_put_contents("log/dy_user_loginInfo_dy".date('Ymd').".txt",$d_url.PHP_EOL,FILE_APPEND);
                                        $d_res = file_get_contents($d_url);
                                        file_put_contents("log/dy_user_loginInfo_dy".date('Ymd').".txt",$d_res.PHP_EOL,FILE_APPEND);
                                        file_put_contents("log/dy_user_loginInfo_dy".date('Ymd').".txt",date('Y-m-d H:i:s').PHP_EOL,FILE_APPEND);

                                        /**
                                         * 用于记录广告数据回传日志，排查广告平台数据与数据库数据对不上的问题
                                         */
                                        $log_params = [
                                            "share_type" => $share_type,
                                            "share_code" => $share_code,
                                            "url" => $d_url,
                                            "res" => $d_res,
                                            "clickid" => $clickid,
                                            "clue_token" => input('clue_token'),
                                            "company_entity" => input('company_entity'),
                                            "account" => input('account'),
                                        ];
                                        $this->save_touliushou_log($log_params,"【抖音小程序】用户注册行为，给巨量引擎回传event_type=0表示激活");




                                        $extend['clickid'] = $clickid;
                                    }

                                    //如果有clue_token字段，说明是(字节系)巨量广告2.0的微信小程序跳转，要用POST方式做数据的回传
                                    $clue_token = input('clue_token');
                                    file_put_contents("log/dy_user_loginInfo_zj".date('Ymd').".txt","clue_token={$clue_token}".PHP_EOL,FILE_APPEND);

                                    //加empty($clickid)是为了防止巨量引擎重复回传
                                    if(empty($clickid) && !empty($clue_token)){
                                        $post_url = "https://clue.oceanengine.com/outer/wechat/applet/token/1794573964023881";

                                        $token = "DA4F57B4A91927287BDB4C22CA1D9817";
                                        $nonce = rand(10000,99999);//随机整数，防止请求被中间劫持篡改
                                        $timestamp = time();//当前时间戳

                                        $collect = [
                                            (string)$token,(string)$nonce,(string)$timestamp,
                                        ];

                                        usort($collect,'strcmp');
                                        $signature = sha1(implode('',$collect));

                                        $post_url .= "?timestamp={$timestamp}&nonce={$nonce}&signature={$signature}";

                                        file_put_contents("log/dy_user_loginInfo_zj".date('Ymd').".txt",$post_url.PHP_EOL,FILE_APPEND);


                                        $post_data = [];
                                        $post_data['clue_token'] = $clue_token;
                                        $post_data['open_id'] = $extend['openid'];
                                        $post_data['event_type'] = "0";//0-激活，1-注册
                                        /*if(isset($res['unionid']) && $res['unionid']){
                                            $post_data['union_id'] = $res['unionid'];
                                        }*/

                                        file_put_contents("log/dy_user_loginInfo_zj".date('Ymd').".txt",json_encode($post_data,JSON_UNESCAPED_UNICODE).PHP_EOL,FILE_APPEND);

                                        $post_res = $this->json_post($post_url,$post_data);
                                        file_put_contents("log/dy_user_loginInfo_zj".date('Ymd').".txt",json_encode($post_res,JSON_UNESCAPED_UNICODE).PHP_EOL,FILE_APPEND);


                                        /**
                                         * 用于记录广告数据回传日志，排查广告平台数据与数据库数据对不上的问题
                                         */
                                        $log_params = [
                                            "share_type" => $share_type,
                                            "share_code" => $share_code,
                                            "url" => $post_url,
                                            "data" => json_encode($post_data,JSON_UNESCAPED_UNICODE),
                                            "res" => json_encode($post_res,JSON_UNESCAPED_UNICODE),
                                            "clickid" => input("clickid"),
                                            "clue_token" => $clue_token,
                                            "company_entity" => input('company_entity'),
                                            "account" => input('account'),
                                        ];
                                        $this->save_touliushou_log($log_params,"【抖音小程序】用户注册行为，给巨量星图回传event_type=0表示激活");






                                        $post_data['event_type'] = "1";//0-激活，1-注册
                                        file_put_contents("log/dy_user_loginInfo_zj".date('Ymd').".txt",json_encode($post_data,JSON_UNESCAPED_UNICODE).PHP_EOL,FILE_APPEND);


                                        $post_res = $this->json_post($post_url,$post_data);
                                        file_put_contents("log/dy_user_loginInfo_zj".date('Ymd').".txt",json_encode($post_res,JSON_UNESCAPED_UNICODE).PHP_EOL,FILE_APPEND);
                                        file_put_contents("log/dy_user_loginInfo_zj".date('Ymd').".txt","————————————————————————————————————————————————————————————————————".PHP_EOL,FILE_APPEND);


                                        /**
                                         * 用于记录广告数据回传日志，排查广告平台数据与数据库数据对不上的问题
                                         */
                                        $log_params = [
                                            "share_type" => $share_type,
                                            "share_code" => $share_code,
                                            "url" => $post_url,
                                            "data" => json_encode($post_data,JSON_UNESCAPED_UNICODE),
                                            "res" => json_encode($post_res,JSON_UNESCAPED_UNICODE),
                                            "clickid" => input("clickid"),
                                            "clue_token" => $clue_token,
                                            "company_entity" => input('company_entity'),
                                            "account" => input('account'),
                                        ];
                                        $this->save_touliushou_log($log_params,"【抖音小程序】用户注册行为，给巨量星图回传event_type=1表示注册");





                                        $extend['clue_token'] = $clue_token;
                                    }


                                }
                            }
                            $pid_channel_id = $pid_channel["id"];
                        }

                    }
                }


                $extend['pid'] = $pid;
                $extend['pid_channel_id'] = $pid_channel_id;
                $extend['share_code'] = $random;
                $extend['share_type'] = $share_type;
                $extend['trackid'] = $trackid;//B站的trackid

                $account = input('account');//此字段来源于fa_user_channel表的url中后面拼接的account字段，原意是用于标记此用户来源于哪一条广告
                if(!empty($account)){
                    $extend['account'] = $account;
                }


                $level_type = input('level_type');//充值等级，用于后续选择充值金额列表展示给用户充值面板
                if(!empty($level_type)){
                    $extend['level_type'] = $level_type;
                }

                $company_entity = input('company_entity');//投流的公司主体
                if(!empty($company_entity)){
                    $extend['company_entity'] = DB::name("user_channel_company_entity")->where("english_name",$company_entity)->value('company_name');
                }

                //存储每次的日志，用于排查问题
                file_put_contents("log/dy_loginInfo".date('Ymd').".txt",date('Y-m-d H:i:s').",code={$code},share_type={$share_type},share_code={$share_code},trackid={$trackid},level_type={$level_type},company_entity={$company_entity}".PHP_EOL,FILE_APPEND);


                $this->auth->register($nickName, $password, $username . '@' . $domain, '', $extend );
                
                $userinfo = $this->auth->getUserinfo();
                $return = array(
                    "openid" => $openid,
                    "token" => $userinfo['token']
                );
            }
            $this->success('获取成功', $return);
		}else{
            $this->error('获取失败');
		} 
    }


    /**
     * 获取用户手机号【作废】
     * @ApiMethod (POST)
     * @param string $code
     *
     */
    public function user_phone(){
        //获取前端传过来的code
        $token = $this->auth->getToken();
        $user = \app\common\library\Token::get($token);
        $code = input('code');
        if(!isset($code) || empty($code)){
            $this->error('非法请求');
        }
        //获取accesstoken
        $accessToken = $this->get_access_token();
        //请求地址
        $url = 'https://api.weixin.qq.com/wxa/business/getuserphonenumber?access_token='.$accessToken;
        //前端传递的code
        //组成数组
        $data=[
            'code'=>$code,
        ];
        //这里要把传递的参数给转成json，不然小程序接口会报数据类型错误。
        $result = json_decode($this->curl_post_https($url,json_encode($data)),true);
        //开始判断获取是否成功
        if($result['errcode'] == '0'){
            //获取成功
            $phone = $result['phone_info']['phoneNumber'];
            $user = DB::name("user")->where("mobile",$phone)->find();

            if($user){
                $this->auth->direct($user['id']);
                $userinfo = $this->auth->getUserinfo();
                $return = array(
                    "mobile" => $phone,
                    "openid" => $user['openid'],
                    "token" => $userinfo['token']
                );
            }else{
                $username = "微信用户".Random::alnum(6);
                $password = Random::alnum(6);
                $domain = request()->host();
                $nickName = $username;
                $system = DB::name("system_info")->where("type",1)->find();
                $extend['episode_script_id'] = $system['episode_script_id'];
                $system_avatar_count = DB::name("system_avatar")->count();
                if($system_avatar_count > 0){
                    $system_avatar_select = DB::name("system_avatar")->select();
                    $avatar_rand = rand(0,$system_avatar_count-1);
                    $extend['avatar'] = $system_avatar_select[$avatar_rand]['image'];
                }else{
                    $extend['avatar'] = $system['avatar'];
                }
                $eng_system = DB::name("system_info")->where("type",2)->find();
                $extend['eng_episode_script_id'] = $eng_system['episode_script_id'];
                $ri_system = DB::name("system_info")->where("type",3)->find();
                $extend['ri_episode_script_id'] = $ri_system['episode_script_id'];
                $han_system = DB::name("system_info")->where("type",4)->find();
                $extend['han_episode_script_id'] = $han_system['episode_script_id'];
                $extend['mobile'] = $phone;
                $extend['reg_type'] = 1;
                $this->auth->register($nickName, $password, $username . '@' . $domain, '', $extend );
                
                $userinfo = $this->auth->getUserinfo();
                $return = array(
                    "mobile" => $phone,
                    "openid" => '',
                    "token" => $userinfo['token']
                );
            }
            $this->success('获取成功', $return);
        }else{
            $this->error('获取失败');
        }
    }

 /**
     * 获取时间戳到毫秒
     * @return bool|string
     */
    public static function getMillisecond(){
        list($msec, $sec) = explode(' ', microtime());
        $msectime =  (float)sprintf('%.0f', (floatval($msec) + floatval($sec)) * 1000);
        return $msectimes = substr($msectime,0,13);
    }
    /**
     * 小程序登录
     *
     * @ApiMethod (POST)
     * @param string $code  code
     * @param string $share_type  推广渠道:1=B站,2=微博,3=快手,4=小红书，5=微信朋友圈,6=视频号,7=抖音,999=其他	
     * @param string $share_code  上级推广码
     */
    public function loginInfo(){
        //接收前台传来的值
        $code=input('code');
        $share_type = input('share_type')?input('share_type'):999;
        $share_code = input('share_code');
        $trackid = input('trackid');//B站的trackid

        //判断是否为空
        if (empty($code)){
            return json(['code'=>0,'data'=>'','mag'=>'参数不正确']);
        }
        $appID = $this->AppId;
        $appSecret = $this->Secret;
        //请求地址
        $url = "https://api.weixin.qq.com/sns/jscode2session?appid=".$appID."&secret=".$appSecret."&js_code=".$code."&grant_type=authorization_code";
        $res = $this->getUrl($url);

        // $res = array(
        //     "openid" => time().rand(1000000,9999999),
        //     "session_key" => time()
        // );

        $random = Random::alnum(6);
        $username = "微信用户".$random;
        $password = $random;
        $domain = request()->host();
        $nickName = $username;
        $model= new \app\admin\model\User();
        $data = $model->where('openid',$res['openid'])->find();
        if (!empty($data)){
            
            if($share_code && $share_type==888){
                $pid_user = DB::name("user")->where("share_code",$share_code)->find();
                $share_notify_data = array(
                    "pid" => $pid_user['id'],
                    "user_id" => $data['id'],
                    "createtime" => time(),
                    "create_time" => date("Y-m-d H:i:s")
                );
                DB::name("share_notify")->insert($share_notify_data);
            }

            //B站那边需要在用户进入小程序，回传这个字段，无论这个用户是新用户还是老用户
            if(isset($data['trackid']) && !empty($data['trackid'])){
                $trackid = $data['trackid'];
                $conv_time = $this->getMillisecond();
                //必须要用真实的trackid给B站回传，否则B站那边会报错
                if(!empty($trackid)){
                    $b_url = "https://cm.bilibili.com/conv/api/conversion/ad/cb/v1?conv_type=FORM_SUBMIT&conv_time={$conv_time}&track_id={$trackid}";
                    file_put_contents("log/user_FORM_SUBMIT_B".date('Ymd').".txt",$b_url.PHP_EOL,FILE_APPEND);
                    $bili_res = file_get_contents($b_url);
                    file_put_contents("log/user_FORM_SUBMIT_B".date('Ymd').".txt",$bili_res.PHP_EOL,FILE_APPEND);
                    file_put_contents("log/user_FORM_SUBMIT_B".date('Ymd').".txt",date('Y-m-d H:i:s').",已注册用户".PHP_EOL,FILE_APPEND);

                    /**
                     * 用于记录广告数据回传日志，排查广告平台数据与数据库数据对不上的问题
                     */
                    $log_params = [
                        "share_type" => $share_type,
                        "share_code" => $share_code,
                        "url" => $b_url,
                        "res" => $bili_res,
                        "trackid" => $trackid,
                        "company_entity" => $data['company_entity'],
                        "account" => $data['account'],
                        'user_id' => $data['id'],
                    ];
                    $this->save_touliushou_log($log_params,"【微信小程序】用户登录行为，给B站回传FORM_SUBMIT");
                }
            }
            $model->where('openid',$res['openid'])->update(['session_key'=>$res['session_key']]);
        }else{
            $extend = ['openid' => $res['openid']];
            $system = DB::name("system_info")->where("type",1)->find();
            $extend['episode_script_id'] = $system['episode_script_id'];
            $system_avatar_count = DB::name("system_avatar")->count();
            if($system_avatar_count > 0){
                $system_avatar_select = DB::name("system_avatar")->select();
                $avatar_rand = rand(0,$system_avatar_count-1);
                $extend['avatar'] = $system_avatar_select[$avatar_rand]['image'];
            }else{
                $extend['avatar'] = $system['avatar'];
            }
            $eng_system = DB::name("system_info")->where("type",2)->find();
            $extend['eng_episode_script_id'] = $eng_system['episode_script_id'];
            $ri_system = DB::name("system_info")->where("type",3)->find();
            $extend['ri_episode_script_id'] = $ri_system['episode_script_id'];
            $han_system = DB::name("system_info")->where("type",4)->find();
            $extend['han_episode_script_id'] = $han_system['episode_script_id'];
            $pid = '';
            $pid_channel_id = 0;
            if($share_code){
//                file_put_contents("user_loginInfo_get.txt",var_export($_GET, true),FILE_APPEND);
//                file_put_contents("user_loginInfo_post.txt",var_export($_POST, true),FILE_APPEND);
                
                $pid_user = DB::name("user")->where("share_code",$share_code)->find();
                if($pid_user){
                    $pid = $pid_user["id"];

                    //判断前端传了company_entity没有，如果没传就给个默认值"未归属的公司主体"
                    $company_entity = input('company_entity');
                    if(empty($company_entity)){
                        $company_entity = "未归属的公司主体";
                    }else {
                        //如果传了，那就查出来是哪个公司主体
                        $company_entity = DB::name("user_channel_company_entity")->where("english_name","=",$company_entity)->value("company_name");
                    }

                    //判断前端传了account没有，如果没传，就给个默认值account0
                    $account = input('account','account0');

                    //判断前端传了level_type没有，如果没传就默认为2
                    $level_type = input('level_type',2);

                    //现在查询条件里的字段都有值了，就可以查user_channel表了
//                    $pid_channel = DB::name("user_channel")->where(array("user_id"=>$pid,"type"=>$share_type))->find();//老的SQL语句
                    $pid_channel = DB::name("user_channel")->where(array("user_id"=>$pid,"type"=>$share_type,"company_entity"=>$company_entity,"account"=>$account,"level_type"=>$level_type))->find();
                    if($pid_channel){
                        //渠道:1=B站,3=快手,4=小红书，5=微信朋友圈,6=视频号,7=抖音
                        if($share_type == 1){//B站
                            file_put_contents("log/user_loginInfo_B".date('Ymd').".txt","trackid=".$trackid.PHP_EOL,FILE_APPEND);

                            //B站回传
                            $conv_time = $this->getMillisecond();
                            //必须要用真实的trackid给B站回传，否则B站那边会报错
                            if(!empty($trackid)){
//                                $trackid = "pbaes.pUNy4MJ2Ys480sM0UwZGtgegI02oMB26nQ0C1alN0X9S2qnwL5ZtrgEPnAOg9rUnk1bPKVb3pr98wisDlbkQBjPv-LMSPjMLoafocZrveO7ybde8VIaOQCAp7Ztjzark0Sy17q5UQdPNQJzmoeZTxHINFQ_3Luy2jYF142sFoVodPmeRBtZGMmC1G1WrvR2w";
                                $b_url = "https://cm.bilibili.com/conv/api/conversion/ad/cb/v1?conv_type=USER_REGISTER&conv_time={$conv_time}&track_id={$trackid}";

                                file_put_contents("log/user_loginInfo_B".date('Ymd').".txt",$b_url.PHP_EOL,FILE_APPEND);
                                $bili_res = file_get_contents($b_url);
                                file_put_contents("log/user_loginInfo_B".date('Ymd').".txt",$bili_res.PHP_EOL,FILE_APPEND);

                                /**
                                 * 用于记录广告数据回传日志，排查广告平台数据与数据库数据对不上的问题
                                 */
                                $log_params = [
                                    "share_type" => $share_type,
                                    "share_code" => $share_code,
                                    "url" => $b_url,
                                    "res" => $bili_res,
                                    "trackid" => $trackid,
                                    "company_entity" => input('company_entity'),
                                    "account" => input('account'),
                                ];
                                $this->save_touliushou_log($log_params,"【微信小程序】用户注册行为，给B站回传USER_REGISTER");


                                //还要回传FORM_SUBMIT
                                $b_url = "https://cm.bilibili.com/conv/api/conversion/ad/cb/v1?conv_type=FORM_SUBMIT&conv_time={$conv_time}&track_id={$trackid}";

                                file_put_contents("log/user_FORM_SUBMIT_B".date('Ymd').".txt",$b_url.PHP_EOL,FILE_APPEND);
                                $bili_res = file_get_contents($b_url);
                                file_put_contents("log/user_FORM_SUBMIT_B".date('Ymd').".txt",$bili_res.PHP_EOL,FILE_APPEND);
                                file_put_contents("log/user_FORM_SUBMIT_B".date('Ymd').".txt",date('Y-m-d H:i:s').",未注册用户".PHP_EOL,FILE_APPEND);

                                /**
                                 * 用于记录广告数据回传日志，排查广告平台数据与数据库数据对不上的问题
                                 */
                                $log_params = [
                                    "share_type" => $share_type,
                                    "share_code" => $share_code,
                                    "url" => $b_url,
                                    "res" => $bili_res,
                                    "trackid" => $trackid,
                                    "company_entity" => input('company_entity'),
                                    "account" => input('account'),
                                ];
                                $this->save_touliushou_log($log_params,"【微信小程序】用户注册行为，给B站回传FORM_SUBMIT");
                            }

                        }else if($share_type == 5){//微信朋友圈(就是广点通,就是腾讯广告)
                            //必须是还没有注册的用户才能绑定渠道关系
                            $isset_user = DB::name("user")->where('openid','=',$extend['openid'])->find();
                            if(empty($isset_user)){
                                $cpa_teng_xun = DB::name("cpa_teng_xun")->where('wechat_openid','=',$extend['openid'])->order("id","desc")->find();
                                if(!empty($cpa_teng_xun)){//监测链接里有这一条openid的话，就对上号了
                                    //要向callback的地址提交一个post请求,先拿到callback地址,然后urldecode一下,最后上报注册信息
                                    $post_url = $cpa_teng_xun['callback'];
                                    $post_url = urldecode($post_url);
                                    $post_data['actions'] = [];
                                    $post_data['actions'][0]['action_type'] = "REGISTER";
                                    $post_data['actions'][0]['action_time'] = time();
                                    $post_data['actions'][0]['user_id']['wechat_app_id'] = $this->AppId;
                                    $post_data['actions'][0]['user_id']['wechat_openid'] = $extend['openid'];
                                    file_put_contents("log/user_loginInfo_gdt".date('Ymd').".txt",$post_url.PHP_EOL,FILE_APPEND);
                                    file_put_contents("log/user_loginInfo_gdt".date('Ymd').".txt",json_encode($post_data,JSON_UNESCAPED_UNICODE).PHP_EOL,FILE_APPEND);
                                    $post_res = $this->json_post($post_url,$post_data);
                                    file_put_contents("log/user_loginInfo_gdt".date('Ymd').".txt",$post_res.PHP_EOL,FILE_APPEND);
                                    file_put_contents("log/user_loginInfo_gdt".date('Ymd').".txt",date('Y-m-d H:i:s').PHP_EOL,FILE_APPEND);
                                    /**
                                     * 用于记录广告数据回传日志，排查广告平台数据与数据库数据对不上的问题
                                     */
                                    $log_params = [
                                        "share_type" => $share_type,
                                        "share_code" => $share_code,
                                        "url" => $post_url,
                                        "data" => json_encode($post_data,JSON_UNESCAPED_UNICODE),
                                        "res" => $post_res,
                                        "tencentid" =>$cpa_teng_xun['id'],
                                        "company_entity" => input('company_entity'),
                                        "account" => input('account'),
                                    ];
                                    $this->save_touliushou_log($log_params,"【微信小程序】用户注册行为，给广点通回传REGISTER");


                                    $post_data['actions'][0]['action_type'] = "ACTIVATE_APP";
                                    file_put_contents("log/user_loginInfo_gdt".date('Ymd').".txt",json_encode($post_data,JSON_UNESCAPED_UNICODE).PHP_EOL,FILE_APPEND);
                                    $post_res = $this->json_post($post_url,$post_data);
                                    file_put_contents("log/user_loginInfo_gdt".date('Ymd').".txt",$post_res.PHP_EOL,FILE_APPEND);
                                    file_put_contents("log/user_loginInfo_gdt".date('Ymd').".txt",date('Y-m-d H:i:s').PHP_EOL,FILE_APPEND);
                                    /**
                                     * 用于记录广告数据回传日志，排查广告平台数据与数据库数据对不上的问题
                                     */
                                    $log_params = [
                                        "share_type" => $share_type,
                                        "share_code" => $share_code,
                                        "url" => $post_url,
                                        "data" => json_encode($post_data,JSON_UNESCAPED_UNICODE),
                                        "res" => $post_res,
                                        "tencentid" =>$cpa_teng_xun['id'],
                                        "company_entity" => input('company_entity'),
                                        "account" => input('account'),
                                    ];
                                    $this->save_touliushou_log($log_params,"【微信小程序】用户注册行为，给广点通回传ACTIVATE_APP");

                                    $extend['tencentid'] = $cpa_teng_xun['id'];
                                }
                            }
                        }else if($share_type == 7){//抖音
                            //必须是还没有注册的用户才能绑定渠道关系
                            $isset_user = DB::name("user")->where('openid','=',$extend['openid'])->find();
                            if(empty($isset_user)){
                                //拿到小程序落地页获得的参数，与监测记录比对
                                $clickid = input('clickid');

                                file_put_contents("log/user_loginInfo_dy".date('Ymd').".txt","clickid={$clickid}".PHP_EOL,FILE_APPEND);

                                if(!empty($clickid)){
                                    $d_url = "https://ad.oceanengine.com/track/activate/?callback={$clickid}&event_type=1";//event_type=1表示注册
                                    file_put_contents("log/user_loginInfo_dy".date('Ymd').".txt",$d_url.PHP_EOL,FILE_APPEND);
                                    $d_res = file_get_contents($d_url);
                                    file_put_contents("log/user_loginInfo_dy".date('Ymd').".txt",$d_res.PHP_EOL,FILE_APPEND);
                                    file_put_contents("log/user_loginInfo_dy".date('Ymd').".txt",date('Y-m-d H:i:s').PHP_EOL,FILE_APPEND);

                                    /**
                                     * 用于记录广告数据回传日志，排查广告平台数据与数据库数据对不上的问题
                                     */
                                    $log_params = [
                                        "share_type" => $share_type,
                                        "share_code" => $share_code,
                                        "url" => $d_url,
                                        "res" => $d_res,
                                        "clickid" => $clickid,
                                        "clue_token" => input('clue_token'),
                                        "company_entity" => input('company_entity'),
                                        "account" => input('account'),
                                    ];
                                    $this->save_touliushou_log($log_params,"【微信小程序】用户注册行为，给巨量引擎回传event_type=1表示注册");


                                    $d_url = "https://ad.oceanengine.com/track/activate/?callback={$clickid}&event_type=0";//event_type=0表示激活
                                    file_put_contents("log/user_loginInfo_dy".date('Ymd').".txt",$d_url.PHP_EOL,FILE_APPEND);
                                    $d_res = file_get_contents($d_url);
                                    file_put_contents("log/user_loginInfo_dy".date('Ymd').".txt",$d_res.PHP_EOL,FILE_APPEND);
                                    file_put_contents("log/user_loginInfo_dy".date('Ymd').".txt",date('Y-m-d H:i:s').PHP_EOL,FILE_APPEND);

                                    /**
                                     * 用于记录广告数据回传日志，排查广告平台数据与数据库数据对不上的问题
                                     */
                                    $log_params = [
                                        "share_type" => $share_type,
                                        "share_code" => $share_code,
                                        "url" => $d_url,
                                        "res" => $d_res,
                                        "clickid" => $clickid,
                                        "clue_token" => input('clue_token'),
                                        "company_entity" => input('company_entity'),
                                        "account" => input('account'),
                                    ];
                                    $this->save_touliushou_log($log_params,"【微信小程序】用户注册行为，给巨量引擎回传event_type=0表示激活");


                                    $extend['clickid'] = $clickid;
                                }

                                //如果有clue_token字段，说明是(字节系)巨量广告2.0的微信小程序跳转，要用POST方式做数据的回传
                                $clue_token = input('clue_token');
                                file_put_contents("log/user_loginInfo_zj".date('Ymd').".txt","clue_token={$clue_token}".PHP_EOL,FILE_APPEND);

                                //加empty($clickid)防止巨量引擎重复回传
                                if(empty($clickid) && !empty($clue_token)){
                                    $post_url = "https://clue.oceanengine.com/outer/wechat/applet/token/1794573964023881";

                                    $token = "DA4F57B4A91927287BDB4C22CA1D9817";
                                    $nonce = rand(10000,99999);//随机整数，防止请求被中间劫持篡改
                                    $timestamp = time();//当前时间戳

                                    $collect = [
                                        (string)$token,(string)$nonce,(string)$timestamp,
                                    ];

                                    usort($collect,'strcmp');
                                    $signature = sha1(implode('',$collect));

                                    $post_url .= "?timestamp={$timestamp}&nonce={$nonce}&signature={$signature}";
                                    file_put_contents("log/user_loginInfo_zj".date('Ymd').".txt",$post_url.PHP_EOL,FILE_APPEND);


                                    $post_data = [];
                                    $post_data['clue_token'] = $clue_token;
                                    $post_data['open_id'] = $extend['openid'];
                                    $post_data['event_type'] = "0";//0-激活，1-注册
                                    /*if(isset($res['unionid']) && $res['unionid']){
                                        $post_data['union_id'] = $res['unionid'];
                                    }*/

                                    file_put_contents("log/user_loginInfo_zj".date('Ymd').".txt",json_encode($post_data,JSON_UNESCAPED_UNICODE).PHP_EOL,FILE_APPEND);

                                    $post_res = $this->json_post($post_url,$post_data);
                                    file_put_contents("log/user_loginInfo_zj".date('Ymd').".txt",json_encode($post_res,JSON_UNESCAPED_UNICODE).PHP_EOL,FILE_APPEND);

                                    /**
                                     * 用于记录广告数据回传日志，排查广告平台数据与数据库数据对不上的问题
                                     */
                                    $log_params = [
                                        "share_type" => $share_type,
                                        "share_code" => $share_code,
                                        "url" => $post_url,
                                        "data" => json_encode($post_data,JSON_UNESCAPED_UNICODE),
                                        "res" => json_encode($post_res,JSON_UNESCAPED_UNICODE),
                                        "clickid" => input("clickid"),
                                        "clue_token" => input('clue_token'),
                                        "company_entity" => input('company_entity'),
                                        "account" => input('account'),
                                    ];
                                    $this->save_touliushou_log($log_params,"【微信小程序】用户注册行为，给巨量星图回传event_type=0表示激活");



                                    $post_data['event_type'] = "1";//0-激活，1-注册
                                    file_put_contents("log/user_loginInfo_zj".date('Ymd').".txt",json_encode($post_data,JSON_UNESCAPED_UNICODE).PHP_EOL,FILE_APPEND);


                                    $post_res = $this->json_post($post_url,$post_data);
                                    file_put_contents("log/user_loginInfo_zj".date('Ymd').".txt",json_encode($post_res,JSON_UNESCAPED_UNICODE).PHP_EOL,FILE_APPEND);
                                    file_put_contents("log/user_loginInfo_zj".date('Ymd').".txt",date('Y-m-d H:i:s').PHP_EOL,FILE_APPEND);
                                    file_put_contents("log/user_loginInfo_zj".date('Ymd').".txt","————————————————————————————————————————————————————————————————————".PHP_EOL,FILE_APPEND);


                                    /**
                                     * 用于记录广告数据回传日志，排查广告平台数据与数据库数据对不上的问题
                                     */
                                    $log_params = [
                                        "share_type" => $share_type,
                                        "share_code" => $share_code,
                                        "url" => $post_url,
                                        "data" => json_encode($post_data,JSON_UNESCAPED_UNICODE),
                                        "res" => json_encode($post_res,JSON_UNESCAPED_UNICODE),
                                        "clickid" => input("clickid"),
                                        "clue_token" => input('clue_token'),
                                        "company_entity" => input('company_entity'),
                                        "account" => input('account'),
                                    ];
                                    $this->save_touliushou_log($log_params,"【微信小程序】用户注册行为，给巨量星图回传event_type=1表示注册");


                                    $extend['clue_token'] = $clue_token;
                                }


                            }
                        }
                        $pid_channel_id = $pid_channel["id"];
                    }
                    
                }
            }
            $extend['pid'] = $pid;
            $extend['user_channel_id'] = $pid_channel_id;
            $extend['share_code'] = $random;
            $extend['share_type'] = $share_type;
            $extend['trackid'] = $trackid;//B站的trackid

            $account = input('account');//此字段来源于fa_user_channel表的url中后面拼接的account字段，原意是用于标记此用户来源于哪一条广告
            if(!empty($account)){
                $extend['account'] = $account;
            }


            $level_type = input('level_type');//充值等级，用于后续选择充值金额列表展示给用户充值面板
            if(!empty($level_type)){
                $extend['level_type'] = $level_type;
            }

            $company_entity = input('company_entity');//投流的公司主体

            if(empty($company_entity)){
                //什么都不做
            }else {
                $insert_company_entity = DB::name("user_channel_company_entity")->where("english_name",$company_entity)->value('company_name');
                if(!empty($insert_company_entity)){
                    $extend['company_entity'] = $insert_company_entity;
                }else {
                    //什么都不做
                }
            }

            //存储每次的日志，用于排查问题
            file_put_contents("log/loginInfo".date('Ymd').".txt",date('Y-m-d H:i:s').",code={$code},share_type={$share_type},share_code={$share_code},trackid={$trackid},level_type={$level_type},company_entity={$company_entity}".PHP_EOL,FILE_APPEND);


            $extend['reg_type'] = 1;
            $this->auth->register($nickName, $password, $username . '@' . $domain, '', $extend );
            $data = $model->where('openid',$res['openid'])->find();
            
            //20240412start
            if($pid_channel_id){
                DB::name("user_channel")->where(array("id"=>$pid_channel_id))->setInc("today_reg_num");
                DB::name("user_channel")->where(array("id"=>$pid_channel_id))->setInc("total_reg_num");
                $channel_data = array(
                    "user_id" => $data['id'],
                    "user_channel_id" => $pid_channel_id,
                    "type" => $share_type,
                    "create_time" => date("Y-m-d H:i:s")
                );
                DB::name("channel_log")->insert($channel_data);
            }

            /**
             *5月9号需求
             * 1.用户第一次分享微信小程序时立刻送1k嘶豆(无论有没有人点击都送这1k)，只有在首次分享的时候送，后续无论分享几次都不送嘶豆
             * 2.点击分享链接进来的用户如果是未注册的新用户，那么分享的那个人再得1k嘶豆，但是进来的新用户不送任何嘶豆
             * 3.用户在进入小程序以后，首页不再有领1W嘶豆的功能了，默认嘶豆数就是0，但是可以看昨夜故事，到摸与不摸的地方弹出充值面板付费
             */


            if($share_code && $share_type==888){
                $pid_user = DB::name("user")->where("share_code",$share_code)->find();
                DB::name("user")->where("id",$pid_user['id'])->setInc("money",1000);
                $money_log = array(
                    "user_id" => $pid_user['id'],
                    "money" => 1000,
                    "before" => $pid_user['money'],
                    "after" => $pid_user['money']+1000,
                    "memo" => "支付挽留推广新用户".$nickName."赠送1000嘶豆",
                    "createtime" => time()
                );
                DB::name("user_money_log")->insert($money_log);

                /**
                 * 这里是孟老师写的新用户点击别人的分享小程序，进来注册并赠送嘶豆的方法
                 * 根据华林的反馈，这里少了一个往share_notify表里添加记录的逻辑，所以在此处加上去
                 */
                $share_notify_data = array(
                    "pid" => $pid_user['id'],
                    "user_id" => $this->auth->id,
                    "createtime" => time(),
                    "create_time" => date("Y-m-d H:i:s")
                );
                DB::name("share_notify")->insert($share_notify_data);
            }
            //20240412end
        }
        $this->auth->direct($data['id']);

        $data['userinfo'] = $this->auth->getUserinfo();
        $this->success('登录成功', $data['userinfo']);
    }


    /**
     * 用户信息
     * @ApiReturnParams   (name="code", type="integer", required=true, sample="0",description="通讯状态，0为失败，1为成功")
     * @ApiReturnParams   (name="msg", type="string", required=true, sample="返回成功",description="返回内容")
     * @ApiReturnParams   (name="data",description="扩展数据返回")
     * @ApiReturnParams   (name="id", type="string", required=true, sample="返回成功",description="用户id")
     * @ApiReturnParams   (name="username", type="string", required=true, sample="返回成功",description="用户名")
     * @ApiReturnParams   (name="nickname", type="string", required=true, sample="返回成功",description="昵称")
     * @ApiReturnParams   (name="email", type="string", required=true, sample="返回成功",description="邮箱")
     * @ApiReturnParams   (name="mobile", type="string", required=true, sample="返回成功",description="手机号")
     * @ApiReturnParams   (name="avatar", type="string", required=true, sample="返回成功",description="头像")
     * @ApiReturnParams   (name="birthday", type="string", required=true, sample="返回成功",description="生日")
     * @ApiReturnParams   (name="bio", type="string", required=true, sample="返回成功",description="签名")
     * @ApiReturnParams   (name="money", type="string", required=true, sample="返回成功",description="余额")
     * @ApiReturnParams   (name="episode_script_id", type="string", required=true, sample="返回成功",description="剧本id")
     * @ApiReturnParams   (name="lang_type", type="string", required=true, sample="返回成功",description="语言类型：1=中文,2=英文")
     */
    public function index()
    {
        $result = DB::name("user")->where("id",$this->auth->id)->field("id,share_code,pid,username,nickname,email,level,mobile,avatar,gender,birthday,bio,money,episode_script_id,eng_episode_script_id,lang_type")->find();
        
        $episode_character = DB::name("episode_character")->where("episode_script_id",$result['episode_script_id'])->select();
        foreach($episode_character as $key => $val){
            $usergood = DB::name("episode_usergood")->where(array("user_id"=>$this->auth->id,"episode_character_id"=>$val['id']))->find();
            if(empty($usergood)){
                $data = array(
                    "user_id" => $this->auth->id,
                    "episode_script_id" => $result['episode_script_id'],
                    "episode_character_id" => $val['id'],
                    "num" => 0,
                    "video_num" => 0,
                    "create_time" => date("Y-m-d H:i:s")
                );
                DB::name("episode_usergood")->insert($data);
            }
        }

        $eng_episode_character = DB::name("episode_character")->where("episode_script_id",$result['eng_episode_script_id'])->select();
        foreach($eng_episode_character as $key => $val){
            $usergood = DB::name("episode_usergood")->where(array("user_id"=>$this->auth->id,"episode_character_id"=>$val['id']))->find();
            if(empty($usergood)){
                $data = array(
                    "user_id" => $this->auth->id,
                    "episode_script_id" => $result['eng_episode_script_id'],
                    "episode_character_id" => $val['id'],
                    "num" => 0,
                    "video_num" => 0,
                    "create_time" => date("Y-m-d H:i:s")
                );
                DB::name("episode_usergood")->insert($data);
            }
        }
        
        // $user_channel = DB::name('user_channel')->where('user_id', $result['id'])->find();
        // if(empty($user_channel)) {
        //     for($i=1;$i<=8;$i++){
        //         if($i == 8){
        //             $type = '999';
        //         }else{
        //             $type = $i;
        //         }
        //         $share_data[] = array(
        //             "pid" => $result['pid'],
        //             "user_id" => $result['id'],
        //             "url" => 'pages/index/index?share_code='.$result['share_code']."&share_type=".$type,
        //             "type" => $type,
        //             "money" => 0,
        //             "total_money" => 0,
        //         );
        //     }
        //     DB::name("user_channel")->insertAll($share_data);
        // }
        
        $this->success('', $result);
    }

    /**
     * 账号密码登录
     *
     * @ApiMethod (POST)
     * @param string $account  账号
     * @param string $password 密码
     */
    public function login()
    {
        $account = $this->request->post('account');
        $password = $this->request->post('password');
        if (!$account || !$password) {
            $this->error(__('Invalid parameters'));
        }
        $ret = $this->auth->login($account, $password);
        if ($ret) {
            $data = ['userinfo' => $this->auth->getUserinfo()];
            $this->success(__('Logged in successful'), $data);
        } else {
            $this->error($this->auth->getError());
        }
    }

    /**
     * 手机验证码登录
     *
     * @ApiMethod (POST)
     * @param string $mobile  手机号
     * @param string $captcha 验证码
     */
    public function mobilelogin()
    {
        $mobile = $this->request->post('mobile');
        $captcha = $this->request->post('captcha');
        if (!$mobile || !$captcha) {
            $this->error(__('Invalid parameters'));
        }
        if (!Validate::regex($mobile, "^1\d{10}$")) {
            $this->error(__('Mobile is incorrect'));
        }
        
        if (!Sms::check($mobile, $captcha, 'mobilelogin')) {
            // $this->error(__('Captcha is incorrect'));
        }
        $user = \app\common\model\User::getByMobile($mobile);
        if ($user) {
            if ($user->status != 'normal') {
                $this->error(__('Account is locked'));
            }
            //如果已经有账号则直接登录
            $ret = $this->auth->direct($user->id);
        } else {
            $ret = $this->auth->register($mobile, Random::alnum(), '', $mobile, []);
        }
        if ($ret) {
            Sms::flush($mobile, 'mobilelogin');
            $data = ['userinfo' => $this->auth->getUserinfo()];
            $this->success(__('Logged in successful'), $data);
        } else {
            $this->error($this->auth->getError());
        }
    }

    /**
     * 注册会员
     *
     * @ApiMethod (POST)
     * @param string $username 用户名
     * @param string $password 密码
     * @param string $email    邮箱
     * @param string $mobile   手机号
     * @param string $code     验证码
     */
    public function register()
    {
        $username = $this->request->post('username');
        $password = $this->request->post('password');
        $email = $this->request->post('email');
        $mobile = $this->request->post('mobile');
        $code = $this->request->post('code');
        if (!$username || !$password) {
            $this->error(__('Invalid parameters'));
        }
        if ($email && !Validate::is($email, "email")) {
            $this->error(__('Email is incorrect'));
        }
        if ($mobile && !Validate::regex($mobile, "^1\d{10}$")) {
            $this->error(__('Mobile is incorrect'));
        }
        $ret = Sms::check($mobile, $code, 'register');
        if (!$ret) {
            $this->error(__('Captcha is incorrect'));
        }
        // $extend = array();
        // $system_avatar_count = DB::name("system_avatar")->count();
        // if($system_avatar_count > 0){
        //     $system_avatar_select = DB::name("system_avatar")->select();
        //     $avatar_rand = rand(0,$system_avatar_count-1);
        //     $extend['avatar'] = $system_avatar_select[$avatar_rand]['image'];
        // }else{
        //     $extend['avatar'] = $system['avatar'];
        // }
        $ret = $this->auth->register($username, $password, $email, $mobile, []);
        if ($ret) {
            $data = ['userinfo' => $this->auth->getUserinfo()];
            $this->success(__('Sign up successful'), $data);
        } else {
            $this->error($this->auth->getError());
        }
    }

    /**
     * 退出登录
     * @ApiMethod (POST)
     */
    public function logout()
    {
        if (!$this->request->isPost()) {
            $this->error(__('Invalid parameters'));
        }
        $this->auth->logout();
        $this->success(__('Logout successful'));
    }

    /**
     * 修改会员个人信息
     *
     * @ApiMethod (POST)
     * @param string $avatar   头像地址
     * @param string $nickname 昵称
     * @param string $gender 性别
     * @param string $birthday 生日
     * @param string $bio      个人简介
     * @param string $lang_type      语言类型:1=中文,2=英文,3=日文,4=韩文
     * @param string $episode_script_id      剧本id
     */
    public function profile()
    {
        $user = $this->auth->getUser();
        $username = $this->request->post('username');
        $nickname = $this->request->post('nickname');
        $birthday = $this->request->post('birthday');
        $bio = $this->request->post('bio');
        $gender = $this->request->post('gender');
        $episode_script_id = $this->request->post('episode_script_id');
        $avatar = $this->request->post('avatar', '', 'trim,strip_tags,htmlspecialchars');
        if ($username) {
            $exists = \app\common\model\User::where('username', $username)->where('id', '<>', $this->auth->id)->find();
            if ($exists) {
                $this->error(__('Username already exists'));
            }
            $user->username = $username;
        }
        if ($nickname) {
            $exists = \app\common\model\User::where('nickname', $nickname)->where('id', '<>', $this->auth->id)->find();
            if ($exists) {
                $this->error(__('Nickname already exists'));
            }
            $user->nickname = $nickname;
        }
        if ($birthday) {
            $user->birthday = $birthday;
        }
        $lang_type = $this->request->post('lang_type');
        if($episode_script_id){
            if($lang_type == 1){
                $user->episode_script_id = $episode_script_id;
            }else{
                $user->eng_episode_script_id = $episode_script_id;
            }
        }
        if($lang_type){
            $user->lang_type = $lang_type;
        }
        if($gender){
            $user->gender = $gender;
        }
        if($bio){
            $user->bio = $bio; 
        }
       if($avatar){
           $user->avatar = $avatar;
       }
        
        $user->save();
        $this->success();
    }

    /**
     * 修改邮箱
     *
     * @ApiMethod (POST)
     * @param string $email   邮箱
     * @param string $captcha 验证码
     */
    public function changeemail()
    {
        $user = $this->auth->getUser();
        $email = $this->request->post('email');
        $captcha = $this->request->post('captcha');
        if (!$email || !$captcha) {
            $this->error(__('Invalid parameters'));
        }
        if (!Validate::is($email, "email")) {
            $this->error(__('Email is incorrect'));
        }
        if (\app\common\model\User::where('email', $email)->where('id', '<>', $user->id)->find()) {
            $this->error(__('Email already exists'));
        }
        $result = Ems::check($email, $captcha, 'changeemail');
        if (!$result) {
            $this->error(__('Captcha is incorrect'));
        }
        $verification = $user->verification;
        $verification->email = 1;
        $user->verification = $verification;
        $user->email = $email;
        $user->save();

        Ems::flush($email, 'changeemail');
        $this->success();
    }

    /**
     * 修改手机号
     *
     * @ApiMethod (POST)
     * @param string $mobile  手机号
     * @param string $captcha 验证码
     */
    public function changemobile()
    {
        $user = $this->auth->getUser();
        $mobile = $this->request->post('mobile');
        $captcha = $this->request->post('captcha');
        if (!$mobile || !$captcha) {
            $this->error(__('Invalid parameters'));
        }
        if (!Validate::regex($mobile, "^1\d{10}$")) {
            $this->error(__('Mobile is incorrect'));
        }
        if (\app\common\model\User::where('mobile', $mobile)->where('id', '<>', $user->id)->find()) {
            $this->error(__('Mobile already exists'));
        }
        $result = Sms::check($mobile, $captcha, 'changemobile');
        if (!$result) {
            $this->error(__('Captcha is incorrect'));
        }
        $verification = $user->verification;
        $verification->mobile = 1;
        $user->verification = $verification;
        $user->mobile = $mobile;
        $user->save();

        Sms::flush($mobile, 'changemobile');
        $this->success();
    }

    
    /**
     * 重置密码
     *
     * @ApiMethod (POST)
     * @param string $mobile      手机号
     * @param string $newpassword 新密码
     * @param string $captcha     验证码
     */
    public function resetpwd()
    {
        $type = $this->request->post("type", "mobile");
        $mobile = $this->request->post("mobile");
        $email = $this->request->post("email");
        $newpassword = $this->request->post("newpassword");
        $captcha = $this->request->post("captcha");
        if (!$newpassword || !$captcha) {
            $this->error(__('Invalid parameters'));
        }
        //验证Token
        if (!Validate::make()->check(['newpassword' => $newpassword], ['newpassword' => 'require|regex:\S{6,30}'])) {
            $this->error(__('Password must be 6 to 30 characters'));
        }
        if ($type == 'mobile') {
            if (!Validate::regex($mobile, "^1\d{10}$")) {
                $this->error(__('Mobile is incorrect'));
            }
            $user = \app\common\model\User::getByMobile($mobile);
            if (!$user) {
                $this->error(__('User not found'));
            }
            $ret = Sms::check($mobile, $captcha, 'resetpwd');
            if (!$ret) {
                $this->error(__('Captcha is incorrect'));
            }
            Sms::flush($mobile, 'resetpwd');
        } else {
            if (!Validate::is($email, "email")) {
                $this->error(__('Email is incorrect'));
            }
            $user = \app\common\model\User::getByEmail($email);
            if (!$user) {
                $this->error(__('User not found'));
            }
            $ret = Ems::check($email, $captcha, 'resetpwd');
            if (!$ret) {
                $this->error(__('Captcha is incorrect'));
            }
            Ems::flush($email, 'resetpwd');
        }
        //模拟一次登录
        $this->auth->direct($user->id);
        $ret = $this->auth->changepwd($newpassword, '', true);
        if ($ret) {
            $this->success(__('Reset password successful'));
        } else {
            $this->error($this->auth->getError());
        }
    }


    

    /**
     * 我的背包
     * @ApiReturnParams   (name="code", type="integer", required=true, sample="0",description="通讯状态，0为失败，1为成功")
     * @ApiReturnParams   (name="msg", type="string", required=true, sample="返回成功",description="返回内容")
     * @ApiReturnParams   (name="data",description="扩展数据返回")
     * @ApiReturnParams   (name="id", type="string", required=true, sample="返回成功",description="背包id")
     * @ApiReturnParams   (name="name", type="string", required=true, sample="返回成功",description="商品名称")
     * @ApiReturnParams   (name="order_no", type="string", required=true, sample="返回成功",description="兑换码编号")
     * @ApiReturnParams   (name="buy_type", type="string", required=true, sample="返回成功",description="来源:1=兑换码兑换,2=购买")
     * @ApiReturnParams   (name="type", type="string", required=true, sample="返回成功",description="道具类型:1=道具,2=抵扣券,3=折扣券")
     * @ApiReturnParams   (name="money", type="string", required=true, sample="返回成功",description="抵扣金额")
     * @ApiReturnParams   (name="ratio", type="string", required=true, sample="返回成功",description="折扣")
     * @ApiReturnParams   (name="door", type="string", required=true, sample="返回成功",description="门槛")
     * @ApiReturnParams   (name="num", type="string", required=true, sample="返回成功",description="数量")
     * @ApiReturnParams   (name="over_num", type="string", required=true, sample="返回成功",description="使用数量")
     * @ApiReturnParams   (name="status", type="string", required=true, sample="返回成功",description="状态:1=未使用,2=部分使用,3=已使用")
     * @ApiReturnParams   (name="send_status", type="string", required=true, sample="返回成功",description="发货状态:1=待发货,2=无需发货,3=申请发货")
     */
    public function getUserBag()
    {
        //未使用未发货
        $result1 = DB::name("user_bag")
                    ->where("user_id =".$this->auth->id." and status = 1 and send_status = 1")
                    ->field("id,user_id,name,system_prop_id,buy_type,type,money,ratio,door,num,over_num,status,send_status,create_time,sum(num) as total_num")
                    ->group("system_prop_id")
                    ->order("id desc")
                    ->select();
        //已使用未发货
        $result2 = DB::name("user_bag")
                    ->where("user_id =".$this->auth->id." and status = 3 and send_status = 1")
                    ->field("id,user_id,name,system_prop_id,buy_type,type,money,ratio,door,num,over_num,status,send_status,create_time,sum(num) as total_num")
                    ->group("system_prop_id")
                    ->order("id desc")
                    ->select();
        //未使用无需发货
        $result3 = DB::name("user_bag")
                    ->where("user_id =".$this->auth->id." and status = 1 and send_status = 2")
                    ->field("id,user_id,name,system_prop_id,buy_type,type,money,ratio,door,num,over_num,status,send_status,create_time,sum(num) as total_num")
                    ->group("system_prop_id")
                    ->order("id desc")
                    ->select();
        //未使用已发货
        $result4 = DB::name("user_bag")
                    ->where("user_id =".$this->auth->id." and status = 1 and send_status = 3")
                    ->field("id,user_id,name,system_prop_id,buy_type,type,money,ratio,door,num,over_num,status,send_status,create_time,sum(num) as total_num")
                    ->group("system_prop_id")
                    ->order("id desc")
                    ->select();
        //已使用已发货
        $result5 = DB::name("user_bag")
                    ->where("user_id =".$this->auth->id." and status = 3 and send_status = 3")
                    ->field("id,user_id,name,system_prop_id,buy_type,type,money,ratio,door,num,over_num,status,send_status,create_time,sum(num) as total_num")
                    ->group("system_prop_id")
                    ->order("id desc")
                    ->select();
        $result = array_merge($result1,$result2,$result3,$result4,$result5);
        // $result = DB::name("user_bag")->where("user_id =".$this->auth->id." and status != 3")->order("id desc")->select();
        foreach ($result as $key => $val){
            $system_prop = DB::name("system_prop")->where("id",$val['system_prop_id'])->find();
            $result[$key]['prop_image'] = $system_prop['image'];
            $result[$key]['prop_blurb'] = $system_prop['blurb'];
            $result[$key]['entity_type'] = $system_prop['entity_type'];
        }
        $this->success('查询成功', $result);
    }

    

    /**
     * 我的优惠券
     * @param string $type      类型:1=折扣券，2=抵扣券
     * @ApiReturnParams   (name="code", type="integer", required=true, sample="0",description="通讯状态，0为失败，1为成功")
     * @ApiReturnParams   (name="msg", type="string", required=true, sample="返回成功",description="返回内容")
     * @ApiReturnParams   (name="data",description="扩展数据返回")
     * @ApiReturnParams   (name="id", type="string", required=true, sample="返回成功",description="背包id")
     * @ApiReturnParams   (name="name", type="string", required=true, sample="返回成功",description="商品名称")
     * @ApiReturnParams   (name="order_no", type="string", required=true, sample="返回成功",description="兑换码编号")
     * @ApiReturnParams   (name="buy_type", type="string", required=true, sample="返回成功",description="来源:1=兑换码兑换,2=购买")
     * @ApiReturnParams   (name="type", type="string", required=true, sample="返回成功",description="道具类型:1=道具,2=抵扣券,3=折扣券")
     * @ApiReturnParams   (name="money", type="string", required=true, sample="返回成功",description="抵扣金额")
     * @ApiReturnParams   (name="ratio", type="string", required=true, sample="返回成功",description="折扣")
     * @ApiReturnParams   (name="door", type="string", required=true, sample="返回成功",description="门槛")
     * @ApiReturnParams   (name="num", type="string", required=true, sample="返回成功",description="数量")
     * @ApiReturnParams   (name="over_num", type="string", required=true, sample="返回成功",description="使用数量")
     * @ApiReturnParams   (name="status", type="string", required=true, sample="返回成功",description="状态:1=未使用,2=部分使用,3=已使用")
     */
    public function getUserCoupon()
    {
        $type = input("type")?input("type"):1;
        if($type == 1){
            $where = 3;
        }else{
            $where = $type;
        }
        $result = DB::name("user_bag")->where("user_id =".$this->auth->id." and status != 3 and type = ".$where)->order("id desc")->select();
        $this->success('查询成功', $result);
    }
    
    
    
    /**
     * 用户充值
     *
     * @ApiMethod (POST)
     * @param string $system_recharge_id  充值配置id
     * @param string $device_type  设备类型：1=安卓，2=IOS
     * @param string $type 充值方式:1=小程序支付,2=抖音支付,3=支付宝支付,4=app支付,5=h5支付	
     */
    public function doAddUserRecharge()
    {
        $system_recharge_id = $this->request->post('system_recharge_id');
        $type = $this->request->post('type')?$this->request->post('type'):1;
        $device_type = $this->request->post('device_type')?$this->request->post('device_type'):1;
        
        if (empty($system_recharge_id)) {
            $this->error("请选择充值配置");
        }
        $system_recharge = DB::name("system_recharge")->where("id",$system_recharge_id)->find();
        if(empty($system_recharge)){
            $this->error("充值配置有误");
        }
        $order_no = "recharge".date("YmdHis").rand(1000,9999);
        // $data = array(
        //     "user_id" => $this->auth->id,
        //     "order_no" => $order_no,
        //     "money" => $system_recharge['money'],
        //     "dou_money" => $system_recharge['dou_money'],
        //     "create_time" => date("Y-m-d H:i:s")
        // );
        $user_find = DB::name("user")->where("id",$this->auth->id)->find();
        if($user_find['share_type'] == 888){
            $share_type = 999;
        }else{
            $share_type = $user_find['share_type'];
        }
        
        if($type == 1 && $device_type == 1){
            //虚拟支付
            // 如果是基础库的wx.requestVirtualPayment，uri固定为requestVirtualPayment
            // $uri = '/xpay/query_user_balance';
            // 此处appkey为假设值，实际使用应根据支付环境(env参数)替换为对应的AppKey
            $appkey = "SgM7386iqymWi0qrj7ReIn7CbgRqLjBA";
            $offerId = '1450217770';
            // $ip = $_SERVER['REMOTE_ADDR'];
            // $data = array(
            //     "openid" => $user_find['openid'],
            //     "env" => 1,
            //     "user_ip" => $ip,
            // );
            // $post_body = json_encode($data);
            // $pay_sig = $this->calc_pay_sig($uri, $post_body, $appkey);
            
            // $signature = $this->calc_signature($post_body, $user_find['session_key']);

            // $access_token = $this->get_access_token();
            // // print_r($access_token);exit;
            // $url = 'https://api.weixin.qq.com/xpay/query_user_balance?access_token='.$access_token.'&pay_sig='.$pay_sig.'&signature='.$signature;
            
            // $res = json_decode($this->json_post($url,$data),true);
            // if($res['errcode'] != 0){
            //     $this->error($res['errmsg']);
            // }else{
                // $balance = $res['balance']/100;
                // if($balance >= $system_recharge['money']){
                //     //余额足够
                //     $result = array(
                //         "pay_status" =>1
                //     );
                //     $this->success("没搞完，别瞎测",$result);
                // }else{
                     // 如果是基础库的wx.requestVirtualPayment，uri固定为requestVirtualPayment
                     $uri = 'requestVirtualPayment';
                     // 此处appkey为假设值，实际使用应根据支付环境(env参数)替换为对应的AppKey
                     $data = array(
                         "offerId" => $offerId,
                         "buyQuantity" => $system_recharge['money']*10*10,
                        //  "buyQuantity" => 1,
                         "env" => 0,
                         "currencyType" => "CNY",
                         "outTradeNo" => $order_no,
                         "attach" => "testdata",
                     );
                    //  $this->error($data);
                     $post_body = json_encode($data);
                     $pay_sig = $this->calc_pay_sig($uri, $post_body, $appkey);
                     $signature = $this->calc_signature($post_body, $user_find['session_key']);
                    //余额不足
                    $data = array(
                        "user_id" => $this->auth->id,
                        "pid" => $user_find['pid'],
                        "user_channel_id" => $user_find['user_channel_id'],
                        "share_type" => $share_type,
                        "order_no" => $order_no,
                        "money" => $system_recharge['money'],
                        "device_type" => $device_type,
                        "dou_money" => $system_recharge['dou_money'],
                        "create_time" => date("Y-m-d H:i:s")
                    );
                    DB::name("user_recharge")->insert($data);
                    
                    $result = array(
                        "pay_status" => 2,
                        "order_id" => $order_no,
                        "buyQuantity" => $system_recharge['money']*10*10,
                        "signature" => $signature,
                        "pay_sig" => $pay_sig
                    );
                file_put_contents("log/xuni_pay".date('Ymd').".txt","pay_sig=".$pay_sig.PHP_EOL,FILE_APPEND);

                    $this->success("提交成功",$result);
                // }
            // }
        }else if($type == 1 && ($device_type == 2 || $device_type == 3)){
            $data = array(
                "user_id" => $this->auth->id,
                "pid" => $user_find['pid'],
                "user_channel_id" => $user_find['user_channel_id'],
                "share_type" => $share_type,
                "order_no" => $order_no,
                "money" => $system_recharge['money'],
                "device_type" => $device_type,
                "dou_money" => $system_recharge['dou_money'],
                "create_time" => date("Y-m-d H:i:s")
            );
            
            DB::name("user_recharge")->insert($data);
            
            $user_info = DB::name("user")->where("id",$this->auth->id)->find();
            $openid = $user_info['openid'];
            $method = 'miniapp'; //小程序支付
            $type = 'wechat';
            $title = "购买商品";
            //回调链接
            $notifyurl = $this->request->root(true) . '/addons/epay/index/notifyOrder/paytype/' . $type;
            $returnurl = $this->request->root(true) . '/h5/#/index/index';
            $response = Service::submitOrder($data['money'], $order_no, $type, $title, $notifyurl, $returnurl, $method, $openid);

            file_put_contents("log/xuni_pay".date('Ymd').".txt","response=".json_encode($response).PHP_EOL,FILE_APPEND);
            $this->success("发起充值成功", $response);
        }elseif($type == 2){
            // $system_recharge['money'] = 0.01;
            $data = array(
                "user_id" => $this->auth->id,
                "pid" => $user_find['pid'],
                "user_channel_id" => $user_find['user_channel_id'],
                "type" => $type,
                "share_type" => $share_type,
                "order_no" => $order_no,
                "money" => $system_recharge['money'],
                "device_type" => $device_type,
                "dou_money" => $system_recharge['dou_money'],
                "create_time" => date("Y-m-d H:i:s")
            );
            DB::name("user_recharge")->insert($data);
            // 请求时间戳
            $timestamp = time();
            // 开发者填入自己的小程序 app_id
            $appId = "tte3e2955f7cd2a7d301";
            // 随机字符串
            $nonceStr = $this->randStr(10);
            // 应用公钥版本,每次重新上传公钥后需要更新,可通过「开发管理-开发设置-密钥设置」处获取
            $keyVersion = "1";
            // 应用私钥,用于加签 重要：1.测试时请修改为开发者自行生成的私钥;2.请勿将示例密钥用于生产环境;3.建议开发者不要将私钥文本写在代码中
            $privateKeyStr = file_get_contents("../addons/epay/certs/privatekey.pem");
            // 生成好的 data  
            $skuId = $system_recharge_id;	//外部商品id，如：号卡商品id、会员充值套餐id、某类服务id、付费工具id等
            $price = $system_recharge['money']*10*10;	//价格 单位：分
            // $price = 1;	//价格 单位：分
            $quantity = 1;	//购买数量	0 < quantity <= 100 
            $title = "充值";	//商品标题，长度 <= 256字节
            $imageList = "";	//商品图片链接，长度 <= 512 字节注意：目前只支持传入一项
            $goods_type = 401;	//商品类型
            $tagGroupId = "tag_group_7272625659888041996";	//交易规则标签组
            $outOrderNo = $order_no;	//外部订单号
            $payExpireSeconds = 3000;	//支付超时时间，单位秒，例如 300 表示 300 秒后过期；不传或传 0 会使用默认值 300，不能超过48小时。
            $orderEntrySchema = "";	//订单详情页
            $data = json_encode(array(
                "skuList" => array(array(
                    "skuId" => "$skuId",
                    "price" => $price,
                    "quantity" => $quantity,
                    "title" => $title,
                    "imageList" => ['https://shsh.vxmeng.com/static/dy_recharge.png'],
                    "type" => $goods_type,
                    "tagGroupId" => $tagGroupId,
                )),
                "outOrderNo" => $outOrderNo,
                "totalAmount" => $price,
                "limitPayWayList" => array(),
                "payExpireSeconds" => $payExpireSeconds,
                "orderEntrySchema" => array("path"=>"pages/index/index","params"=>json_encode(array("recharge_id"=>"$skuId")))
            ),JSON_UNESCAPED_UNICODE | JSON_UNESCAPED_SLASHES);
            // $data = "{\"skuList\":[{\"skuId\":\"1\",\"price\":9999,\"quantity\":1,\"title\":\"标题\",\"imageList\":[\"https://shsh.vxmeng.com/static/dy_recharge.png\"],\"type\":401,\"tagGroupId\":\"idxxx\"}],\"outOrderNo\":\"1213\",\"totalAmount\":9999,\"limitPayWayList\":[],\"payExpireSeconds\":3000,\"orderEntrySchema\":{\"path\":\"page/index/index\",\"params\":\"{\\\"poi\\\":\\\"6601248937917548558\\\",\\\"aweme_useTemplate\\\":1}\"}}";

            $byteAuthorization = $this->getByteAuthorization($privateKeyStr, $data, $appId, $nonceStr, $timestamp, $keyVersion);
            $result = array(
                "data_value" => $data,
                "byteAuthorization_value" => $byteAuthorization
            );
            $this->success('发起充值成功',$result);
        }else{
            $this->success("暂无充值方式");
        }
    }
    
    function calc_pay_sig($uri, $post_body, $appkey) {
        // pay_sig签名算法
        $need_sign_msg = $uri . '&' . $post_body;
        $pay_sig = hash_hmac('sha256', $need_sign_msg, $appkey);
        return $pay_sig;
    }
    function calc_signature($post_body, $session_key) {
        // 用户登录态signature签名算法
        $need_sign_msg = $post_body;
        $signature = hash_hmac('sha256', $need_sign_msg, $session_key);
        return $signature;
    }
    
    function getByteAuthorization($privateKeyStr, $data, $appId, $nonceStr, $timestamp, $keyVersion) {
		$byteAuthorization = '';
		// 读取私钥
		$privateKey = openssl_pkey_get_private($privateKeyStr);
			if (!$privateKey) {
				throw new InvalidArgumentException("Invalid private key");
			}
		// 生成签名
		$signature = $this->getSignature("POST", "/requestOrder", $timestamp, $nonceStr, $data, $privateKey);
		if ($signature === false) {
			return null;
		}
		// 构造 byteAuthorization
		$byteAuthorization = sprintf("SHA256-RSA2048 appid=%s,nonce_str=%s,timestamp=%s,key_version=%s,signature=%s", $appId, $nonceStr, $timestamp, $keyVersion, $signature);
		return $byteAuthorization;
	}

	function getSignature($method, $url, $timestamp, $nonce, $data, $privateKey) {
		// printf("method:%s\n url:%s\n timestamp:%s\n nonce:%s\n data:%s", $method, $url, $timestamp, $nonce, $data);
		$targetStr = $method. "\n" . $url. "\n" . $timestamp. "\n" . $nonce. "\n" . $data. "\n";
		openssl_sign($targetStr, $sign, $privateKey, OPENSSL_ALGO_SHA256);
		$sign = base64_encode($sign);
		return $sign;
	}

	function randStr($length = 8) {
		$chars = 'abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789';
		$str = '';
		for ($i = 0; $i < $length; $i++) {
			$str .= $chars[mt_rand(0, strlen($chars) - 1)];
		}
		return $str;
	}
    
    /**
     * 意见反馈
     *
     * @ApiMethod (POST)
     * @param string $remark  反馈内容
     */
    public function doAddUserMessage()
    {
        $remark = $this->request->post('remark');
        if (!$remark) {
            $this->error("反馈内容不能为空");
        }
        $data = array(
            "user_id" => $this->auth->id,
            "remark" => $remark,
            "create_time" => date("Y-m-d H:i:s")
        );
        DB::name("user_message")->insert($data);
        $this->success("反馈成功");
    }
    
     /**
     * 修改分辨率
     *
     * @ApiMethod (POST)
     * @param string $resolution_ratio  分辨率
     */
    public function doEditResolutionRatio()
    {
        $user = $this->auth->getUser();
        $resolution_ratio = $this->request->post('resolution_ratio')?$this->request->post('resolution_ratio'):'4k';
        if($resolution_ratio != '4k' && $resolution_ratio != '1080p' && $resolution_ratio != '720p'){
            $this->error("分辨率有误");
        }
        $user->resolution_ratio = $resolution_ratio;
        $user->save();

        $this->success("修改成功");
    }
    
    /**
     * 赠送及首充状态
     */
    public function getUserGive()
    {
        $user = DB::name("user")->where("id",$this->auth->id)->find();
        $system = DB::name("system_info")->where("type",$user['lang_type'])->find();
        $user_recharge = DB::name("user_recharge")->where(array("user_id"=>$this->auth->id,"status"=>2))->count();
        if($user_recharge > 0){
            $is_recharge = 1;
        }else{
            $is_recharge = 2;
        }
        $result = array(
            "is_give" => $user['is_give'],
            "give_money" => $system['give_money'],
            "is_recharge" => $is_recharge
        );
        $this->success("查询成功",$result);
    }
    
    /**
     * 领取注册嘶豆
     *
     * @ApiMethod (POST)
     */
    public function doAddRegGiveMoney()
    {
        $user = DB::name("user")->where("id",$this->auth->id)->find();
        if($user['is_give'] != 1){
            $this->error("您已领取过注册嘶豆，不可重复领取");
        }
        $system = DB::name("system_info")->where("type",$user['lang_type'])->find();
        if($system['give_money'] && $system['give_money'] > 0){
            DB::name("user")->where("id",$this->auth->id)->setInc("money",$system['give_money']);
            DB::name("user")->where("id",$this->auth->id)->update(array("is_give"=>2));
            $money_log = array(
                "user_id" => $this->auth->id,
                "money" => $system['give_money'],
                "before" => $user['money'],
                "after" => $user['money']+$system['give_money'],
                "memo" => "领取注册赠送".$system['give_money']."嘶豆",
                "createtime" => time()
            );
            DB::name("user_money_log")->insert($money_log);
            $this->success("领取成功");
        }else{
            $this->error("不可领取");
        }  
    }
    
    
    /**
     * 充值记录
     * @param string $type  查询类型:1=全部,2=最近1年，3=最近一月
     * @param string $page  页码，默认为1
     * @param string $page_size  每页数量，默认15
     * @ApiReturnParams   (name="code", type="integer", required=true, sample="0",description="通讯状态，0为失败，1为成功")
     * @ApiReturnParams   (name="msg", type="string", required=true, sample="返回成功",description="返回内容")
     * @ApiReturnParams   (name="data",description="扩展数据返回")
     * @ApiReturnParams   (name="id", type="string", required=true, sample="返回成功",description="id")
     * @ApiReturnParams   (name="order_no", type="string", required=true, sample="返回成功",description="订单编号")
     * @ApiReturnParams   (name="money", type="string", required=true, sample="返回成功",description="充值金额")
     * @ApiReturnParams   (name="dou_money", type="string", required=true, sample="返回成功",description="获得嘶豆")
     * @ApiReturnParams   (name="type", type="string", required=true, sample="返回成功",description="充值方式:1=小程序支付,2=抖音支付,3=支付宝支付,4=app支付,5=h5支付")
     * @ApiReturnParams   (name="status", type="string", required=true, sample="返回成功",description="订单状态:1=支付中,2=支付成功,3=支付失败")
     * @ApiReturnParams   (name="create_time", type="string", required=true, sample="返回成功",description="发起时间")
     * @ApiReturnParams   (name="pay_time", type="string", required=true, sample="返回成功",description="支付时间")
     */
    public function getUserRecharge()
    {
        $where = "user_id =".$this->auth->id;
        $type = input("type")?input("type"):1;
        if($type == 2){
            $where .= " and create_time like '%".date("Y")."%'";
        }else if($type == 3){
            $where .= " and create_time like '%".date("Y-m")."%'";
        }
        $page = input("page")?input("page"):1;
        $page_size = input("page_size")?input("page_size"):15;
        $list = DB::name("user_recharge")->where($where)->order("id desc")->page($page,$page_size)->select();
        
        $result['list'] = $list;
        $result['total'] = DB::name("user_recharge")->where($where)->count();
        $this->success('查询成功', $result);
    }


    /**
     * 资金记录
     * @param string $type  查询类型:1=全部,2=最近1年，3=最近一月
     * @param string $page  页码，默认为1
     * @param string $page_size  每页数量，默认15
     * @ApiReturnParams   (name="code", type="integer", required=true, sample="0",description="通讯状态，0为失败，1为成功")
     * @ApiReturnParams   (name="msg", type="string", required=true, sample="返回成功",description="返回内容")
     * @ApiReturnParams   (name="data",description="扩展数据返回")
     * @ApiReturnParams   (name="id", type="string", required=true, sample="返回成功",description="id")
     * @ApiReturnParams   (name="money", type="string", required=true, sample="返回成功",description="变更金额")
     * @ApiReturnParams   (name="before", type="string", required=true, sample="返回成功",description="变更前余额")
     * @ApiReturnParams   (name="after", type="string", required=true, sample="返回成功",description="变更后余额")
     * @ApiReturnParams   (name="memo", type="string", required=true, sample="返回成功",description="备注")
     * @ApiReturnParams   (name="createtime", type="string", required=true, sample="返回成功",description="发起时间")
     */
    public function getUserMoneyLog()
    {
//        $this->auth->id = 26;
        $where = "user_id =".$this->auth->id;
        $type = input("type")?input("type"):1;
        if($type == 2){
            $time = strtotime(date("Y-01-01 00:00:00"));
            $where .= " and createtime >".$time;
        }else if($type == 3){
            $time = strtotime(date("Y-m-01 00:00:00"));
            $where .= " and createtime >".$time;
        }
        
        $page = input("page")?input("page"):1;
        $page_size = input("page_size")?input("page_size"):15;
        $list = DB::name("user_money_log")->where($where)->order("id desc")->page($page,$page_size)->select();
        foreach ($list as $key => $value) {
            $list[$key]['create_time'] = date("Y-m-d H:i:s",$value['createtime']);
        }
        $result['list'] = $list;
        $result['total'] = DB::name("user_money_log")->where($where)->count();
        $this->success('查询成功', $result);
    }
}
